package com.an.framework;

import java.sql.SQLException;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.druid.pool.DruidDataSource;

/**
 * ClassName: MyBatisConf <br/>
 * Function: Mybatis配置. <br/>
 * Reason: Mybatis配置. <br/>
 * date: 2017年11月8日 上午9:43:38 <br/>
 *
 * @author atc
 * @version 1.0.0
 * @since JDK 1.8
 */
@Configuration
@EnableTransactionManagement
@MapperScan("com.an.**.dao")
public class MyBatisConfig {

	private static final Logger logging = LoggerFactory.getLogger(MyBatisConfig.class);
	/**
	 * sqlSessionFactory:MyBatisSqlSessionFactory对象. <br/>
	 *
	 * @author atc
	 * @param dataSource
	 *            数据源
	 * @return SqlSessionFactory
	 * @throws Exception
	 * @since JDK 1.8
	 */
	@Bean
	@Autowired
	public SqlSessionFactory sqlSessionFactory(@Qualifier("druidDataSource")DruidDataSource dataSource) throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		// resolver.getResources("classpath:/mapper/*.xml")
		// 扫描到MyBatis的mapper文件
		bean.setMapperLocations(resolver.getResources("classpath:/mapper/mysql/*.xml"));
		logging.info("Mybatis配置SqlSessionFactory成功！！");
		return bean.getObject();
	}

	@Bean
	@Autowired
	public PlatformTransactionManager transactionManager(DruidDataSource dataSource) throws SQLException {
		return new DataSourceTransactionManager(dataSource);
	}

}
